//
//  Normal Trooper.m
//  DefenseSummoner
//
//  Created by vupham on 5/23/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "Enemy.h"
#import "PlayScreen.h"
#import "iCoreGUIController.h"

@implementation Enemy

@synthesize nextHeadingPoint, fly, opponent, reachSummoner;

-(id)initEnemyWith:(GameLayer *)_gameLayer{
    self=[super initCharacterWith:_gameLayer];
    direction=NO_DIRECTION;
    moneyOnDie = 0;
    fly = NO;
    return self;
}

-(void)update:(ccTime)_timeUpdate {    
    if(HP>0){
        if (!inBattle){
            [self moveOnTheRoad];
        }
        if (reachSummoner){
            //fixed
            if (handler.mainGUIController.playerData.life==0){
                [self animationBattle];
            }
            else if (handler.mainGUIController.playerData.life>0){
                HP=0;
                [self updateBloodMeter];
            }
            //end fixed
            handler.mainGUIController.playerData.life--;
            [((PlayScreen*)handler) drawPlayerInfo];
        }
    }
    else{
        //[spriteBody stopAllActions];
        if(!die){
            //recently edited
            if (!reachSummoner){
                handler.mainGUIController.playerData.money+=moneyOnDie;
                [((PlayScreen*)handler) drawPlayerInfo];
            }
            //end recently edited    
            [spriteBody stopAllActions];
            [self animationDie];
        }
        
    }
}

-(void)moveOnTheRoad{
    if (nextHeadingPoint<road.count){
        CGPoint nextPoint=[[road objectAtIndex:nextHeadingPoint] CGPointValue];
        CGPoint lastPoint=[[road objectAtIndex:nextHeadingPoint-1] CGPointValue];
        CGPoint vector=ccp(nextPoint.x-lastPoint.x ,nextPoint.y-lastPoint.y);
        //calculate the direction of the enemy
        if(vector.y == 0){ 
            vector.y = 0.000001f; 
        }
        float radians = atan(vector.x/vector.y);
        if(vector.y < 0){ 
            radians += PI;
        }
        CGPoint normalVector = ccp(sin(radians), cos(radians));
        //update the enemy's position based on the direction and enemy's speed
        spriteBody.position=ccp(spriteBody.position.x+normalVector.x*speed,spriteBody.position.y+normalVector.y*speed);
        //calculate the degree of the enemy's direction to see which direction he's using
        float degrees = [self radiansToDegrees:radians];
        //NSLog(@"The degree is %f",degrees);
        int nextDirection=NO_DIRECTION;
        if(degrees >= 45.0 && degrees < 125.0){
            nextDirection = DIRECTION_LEFT;
        }else if(degrees >= -45.0 && degrees < 45.0){
            nextDirection = DIRECTION_UP;
        }else if(degrees >= 125.0 && degrees <215.0){
            nextDirection = DIRECTION_DOWN;
        }else{
            nextDirection = DIRECTION_RIGHT;
        }
        //if the enemy's direction is different from the his current direction then change animation
        if(nextDirection!=direction){
            [self loadAnimationBasedOnDirection:nextDirection];
            direction=nextDirection;
        }
        //if enemy got past the point then proceed to next point
        if([self ifEnemyGotPastPoint:[[road objectAtIndex:nextHeadingPoint] CGPointValue]]){
            nextHeadingPoint++;
            /*if(nextHeadingPoint == road.count)
                [self runOverDestination];*/
        }
        //NSLog(@"Sprite X= %f, Sprite Y= %f",sprite.position.x,sprite.position.y);
    }
}

-(BOOL)ifEnemyGotPastPoint:(CGPoint)_point{
    if(direction==DIRECTION_UP && spriteBody.position.y>_point.y){
        return YES;
    }
    else if(direction==DIRECTION_DOWN && spriteBody.position.y<_point.y){
        return YES;
    }
    else if(direction==DIRECTION_LEFT && spriteBody.position.x>_point.x){
        return YES;
    }
    else if(direction==DIRECTION_RIGHT && spriteBody.position.x<_point.x){
        return YES;
    }
    return NO;
}

-(float)vectorToRadians:(CGPoint)vector{
	if(vector.y == 0){ vector.y = 0.000001f; }
	float baseRadians = atan(vector.x/vector.y);
	if(vector.y < 0){ baseRadians += PI; }	//Adjust for -Y
	return baseRadians;
}

-(CGPoint)radiansToVector:(float)radians{
	return ccp(sin(radians-PI/2), cos(radians-PI/2));
}

-(float)radiansToDegrees:(float)r{
	return r * (180/PI);
}

-(CGPoint)roundPoint:(CGPoint)_point{
    return CGPointMake(roundf(_point.x),roundf(_point.y));
}

-(void)runOverDestination {
    [(PlayScreen *)handler enemyRunOverDestination:self];
}

-(CGPoint)getPositionAfterTime:(float)_time {
    NSTimeInterval screenFPS = [[CCDirector sharedDirector] animationInterval];

    if (nextHeadingPoint<road.count){
        CGPoint nextPoint=[[road objectAtIndex:nextHeadingPoint] CGPointValue];
        CGPoint lastPoint=[[road objectAtIndex:nextHeadingPoint-1] CGPointValue];
        CGPoint vector=ccp(nextPoint.x-lastPoint.x ,nextPoint.y-lastPoint.y);

        if(vector.y == 0){ 
            vector.y = 0.000001f; 
        }
        float radians = atan(vector.x/vector.y);
        if(vector.y < 0){ 
            radians += PI;
        }
        CGPoint normalVector = ccp(sin(radians), cos(radians));

        CGPoint newPosition=ccp(spriteBody.position.x + _time / screenFPS * normalVector.x * speed, spriteBody.position.y + _time / screenFPS * normalVector.y *speed);
        
        return newPosition;
    }
    
    return spriteBody.position;
}

-(float)remainDistanceToDes {
    float distanceRemain = 0;
    
    if(nextHeadingPoint < road.count) {
        CGPoint lastPoint = spriteBody.position;
        
        for(int i = nextHeadingPoint; i < road.count; i++) {
            CGPoint nextPoint=[[road objectAtIndex:i] CGPointValue];
            distanceRemain += sqrtf(powf(nextPoint.x - lastPoint.x, 2) + powf(nextPoint.y - lastPoint.y, 2));
            lastPoint = nextPoint;
        }
    }

    return distanceRemain;
}

-(void)battle {
    if([handler.listGameObject containsObject:opponent]){
        if(!handler.mainGUIController.isMuteSound) {
            [handler.mainGUIController playEffect:AUDIO_SOLDIER_ATTACK];
        }
        
        [opponent animationHit];
        opponent.HP-=damage;
        [opponent updateBloodMeter];
    }
    else{
        inBattle=NO;
    }
}

-(void)animationDie {
    [super animationDie];
    //fixed
    if (!reachSummoner){
        CCLabelTTF *moneyDie = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"+ $%d", moneyOnDie] fontName:FONT_COMIC_BOOK fontSize:11];
        moneyDie.color = ccc3(255, 255, 64);
        moneyDie.position = ccp(spriteBody.contentSize.width/2, spriteBody.contentSize.height + moneyDie.contentSize.height/2);
        [spriteBody addChild:moneyDie];
    }
}

-(void)dealloc {
    [super dealloc];
}

@end
